package com.jht.bletool2java.activity.blepage.fragment.blecontrol;

import android.app.Activity;
import android.bluetooth.BluetoothGatt;
import android.bluetooth.BluetoothGattCharacteristic;
import android.bluetooth.BluetoothGattDescriptor;
import android.bluetooth.BluetoothGattService;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.ExpandableListView;
import android.widget.LinearLayout;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import com.hjq.xtoast.XToast;
import com.jht.bletool2java.BLEApplication;
import com.jht.bletool2java.R;
import com.jht.bletool2java.activity.blepage.adapter.ExpandableLvBTAdapter;
import com.jht.bletool2java.activity.homepage.fragment.bledevice.bean.BLEDevice;
import com.wang.avi.AVLoadingIndicatorView;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import static com.jht.bletool2java.service.BLEService.ACTION_GATT_CONNECTED;
import static com.jht.bletool2java.service.BLEService.ACTION_GATT_DISCONNECTED;
import static com.jht.bletool2java.service.BLEService.ACTION_GATT_SERVICES_DISCOVERED;
import static com.jht.bletool2java.service.BLEService.ACTION_MTU_CHANGE;
import static com.jht.bletool2java.service.BLEService.ACTION_NOTIFY_DATA;
import static com.jht.bletool2java.service.BLEService.ACTION_READ_DATA_OK;
import static com.jht.bletool2java.service.BLEService.ACTION_WRITE_DATA_OK;


public class BLEControlFragment extends Fragment implements IBLEControl.UI, ExpandableLvBTAdapter.Callback {
    private static final String TAG = "BLEServiceFragment";

    private BLEDevice bluetoothDevice;
    private ExpandableListView mElvAllServices;
    private LinearLayout mLlAviParent;
    private AVLoadingIndicatorView mAvi;
    private BluetoothGatt bluetoothGatt;
    private LinearLayout mLlLvParent;
    private ExpandableLvBTAdapter expandableLvBTAdapter = null;
    private List<BluetoothGattCharacteristic> characteristicsAllChild = new ArrayList<>();
    private IBLEControl.Presenter presenter;
    private BLEStateReceiver bleStateReceiver = new BLEStateReceiver();

    public BLEControlFragment(BLEDevice ble_device) {
        bluetoothDevice = ble_device;
        presenter = new BLEControlPresenter(this);
    }

    public static BLEControlFragment newInstance(BLEDevice ble_device) {
        return new BLEControlFragment(ble_device);
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(ACTION_GATT_CONNECTED);
        intentFilter.addAction(ACTION_GATT_DISCONNECTED);
        intentFilter.addAction(ACTION_GATT_SERVICES_DISCOVERED);
        intentFilter.addAction(ACTION_MTU_CHANGE);
        intentFilter.addAction(ACTION_READ_DATA_OK);
        intentFilter.addAction(ACTION_NOTIFY_DATA);
        intentFilter.addAction(ACTION_WRITE_DATA_OK);
        BLEApplication.getBLEApplicationContext().registerReceiver(bleStateReceiver, intentFilter);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_all_ble_services, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        mElvAllServices = view.findViewById(R.id.elv_all_services);
        mLlAviParent = view.findViewById(R.id.ll_avi_parent);
        mAvi = view.findViewById(R.id.avi);
        mLlLvParent = view.findViewById(R.id.ll_lv_parent);
        //连接蓝牙
        presenter.connectBLE(bluetoothDevice);
    }



    private void closeProgress() {
        mLlAviParent.setVisibility(View.GONE);
    }


    private void initExpandListView(List<BluetoothGattService> services, Map<String, List<BluetoothGattCharacteristic>> uuid_map_char) {
        expandableLvBTAdapter = new ExpandableLvBTAdapter(BLEApplication.getBLEApplicationContext(),services, uuid_map_char);
        for (BluetoothGattService bluetoothGattService : services) {
            List<BluetoothGattCharacteristic> characteristics = bluetoothGattService.getCharacteristics();
            characteristicsAllChild.addAll(characteristics);
        }
        expandableLvBTAdapter.setCallback(this);
        mElvAllServices.setAdapter(expandableLvBTAdapter);

        mLlLvParent.setVisibility(View.VISIBLE);
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        Log.d(TAG, "onDestroy: ");
        BLEApplication.getBLEApplicationContext().unregisterReceiver(bleStateReceiver);
        presenter.closeConnect();
    }

    @Override
    public void read(BluetoothGattCharacteristic characteristic) {
        presenter.readGatt(characteristic);
    }

    /**
     * 1.打开数据输入窗口让用户输入命令
     * 2.通过调用presenter.writeGatt方法发送命令
     *
     * @param characteristic 需要被操作的蓝牙特征
     */
    @Override
    public void write(final BluetoothGattCharacteristic characteristic) {
        Log.d(TAG, "write: 暂时省略。。");

    }

    @Override
    public void closeNotify(BluetoothGattCharacteristic characteristic) {
        presenter.enableNotify(characteristic,false);
    }

    @Override
    public void CharacteristicNotify(BluetoothGattCharacteristic characteristic) {
        presenter.enableNotify(characteristic,true);
    }

    @Override
    public void CharacteristicIndicate(BluetoothGattCharacteristic characteristic) {
        presenter.enableIndication(characteristic,true);
    }

    public void clear() {
        if (bluetoothGatt != null) {
            bluetoothGatt.disconnect();
            bluetoothGatt.close();
            bluetoothGatt = null;
        }
    }

    private class BLEStateReceiver extends BroadcastReceiver {

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            switch (action) {
                case ACTION_GATT_CONNECTED:
                    break;
                case ACTION_GATT_DISCONNECTED:
                    break;
                case ACTION_GATT_SERVICES_DISCOVERED:
                    closeProgress();
                    initExpandListView(presenter.getAllServices(),presenter.getServicesCharacteristicsMap());
                    break;
                case ACTION_READ_DATA_OK:
                    break;
                case ACTION_WRITE_DATA_OK:
                    break;
                case ACTION_NOTIFY_DATA:
                    break;
                case ACTION_MTU_CHANGE:
                    break;
            }
        }
    }
}